package com.osdp.gateway.service.impl;

import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.osdp.gateway.service.INacosService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Properties;

@Slf4j
@Service
public class NacosServiceImpl implements INacosService {

    private ConfigService getConfigService(String serverAddr, String namespace){
        Properties prop = new Properties();
        prop.put(PropertyKeyConst.SERVER_ADDR,serverAddr);
        prop.put(PropertyKeyConst.NAMESPACE,namespace);
        ConfigService config = null;
        try {
            config = ConfigFactory.createConfigService(prop);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return config;
    }

    @Override
    public boolean saveConfig(String serverAddr, String namespace, String group, String dataId, String content) {
        ConfigService config = this.getConfigService(serverAddr,namespace);
        if(config == null){
            if(log.isDebugEnabled()) {log.debug("获取NACOS配置中心失败");}
            return false;
        }
        try {
            config.publishConfig(dataId,group,content);
        } catch (NacosException e) {
            if(log.isDebugEnabled()){ log.debug("NACOS配置中心dataId:{},group:{},保存content:{}失败");}
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public String getConfig(String serverAddr, String namespace, String group, String dataId) {
        ConfigService config = this.getConfigService(serverAddr,namespace);
        String content = null;
        try {
            content = config.getConfig(dataId,group,3000);
        } catch (NacosException e) {
            if(log.isDebugEnabled()){ log.debug("NACOS配置中心dataId:{},group:{},获取content:{}失败");}
            e.printStackTrace();
        }
        return content;
    }
}
